<template>
  <div class="userContainer">
    <div class="searchRow">
      <div class="inputRow">
        <div class="inputBox">
          <div class="labelText">{{ $t('common.username') }}：</div>
          <a-input v-model:value="queryForm.pageModel.query.user_name0" :placeholder="globalI18n.t('common.username')"
            :allowClear="true"></a-input>
        </div>
      </div>
      <div class="btnBox">
        <a-button type="primary" @click="getTableData()" class="queryBtn">
          查询
        </a-button>
        <a-button class="resetBtn" @click="reset">{{ $t('common.reset') }}</a-button>
      </div>
    </div>

    <div class="tableOperation">
      <div class="operationBtn">
        <a-button type="primary" @click="showAddModel" class="queryBtn">
          {{ $t('common.add') }}
        </a-button>
      </div>
      <a-table :columns="tableData.columns" :pagination="pagination" :data-source="tableData.data">
        <template #headerCell="{ column }">
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.avatar"></a-avatar>
          </template>
          <template v-if="column.key === 'sex'">
            <span v-if="record.sex === 0" style="color: skyblue;">
              <ManOutlined />男
            </span>
            <span v-else-if="record.sex === 1" style="color: brown;">
              <WomanOutlined />女
            </span>
            <span v-else>--</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag v-if="record.status === 0" color="#c9c5c5">禁用</a-tag>
            <a-tag v-else-if="record.status === 1" color="#87d068">启用</a-tag>
          </template>
          <template v-else-if="column.key === 'roleName'">
            <a-tag color="purple">{{ record.roleName }}</a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <span>
              <a class="actionBtn" @click="handleDeleteUser(record.id)">删除</a>
              <a-divider type="vertical" />
              <a class="actionBtn" @click="showEditModel(record)">编辑</a>
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <a-modal v-model:open="open1" :title="modelTitle" @ok="handleAddUser">
      <template #footer>
        <a-button class="cancelBtn" key="back" @click="handleCancel()">取消</a-button>
        <a-button class="confirmBtn" key="submit" type="primary" :loading="loading1" @click="handleAddUser">{{
          $t('common.confirm') }}</a-button>
      </template>

      <a-form ref="formRef" :model="editRecord" :rules="rules" :label-col="{ span: 4 }">
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="editRecord.userName" disabled />
        </a-form-item>
        <a-form-item label="昵称" name="nickName">
          <a-input v-model:value="editRecord.nickName" />
        </a-form-item>
        <a-form-item label="角色" name="roleId">
          <a-select v-model:value="editRecord.roleId" :options="roleOptions"></a-select>
        </a-form-item>
        <a-form-item label="性别" name="sex">
          <a-select v-model:value="editRecord.sex" :options="sexOptions"></a-select>
        </a-form-item>
        <a-form-item label="电话" name="phone">
          <a-input v-model:value="editRecord.phone" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="editRecord.email" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="editRecord.remark" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-switch v-model:checked="editRecord.status1" checked-children="启用" un-checked-children="禁用" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { deleteUser, findUserPage, editUserInfo, addUser } from '@/api/user';
import { findRoleList } from '@/api/role';
import { ExclamationCircleOutlined, WomanOutlined, ManOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

const formRef = ref(null);
// 弹框标题
const modelTitle = ref('');
const sexOptions = [
  { label: '男', value: 0 },
  { label: '女', value: 1 }
];
// 国际化
const globalI18n = useI18n();
// 编辑/新增用户弹框
const loading1 = ref(false);
// 编辑/新 用户参数
const editRecord = reactive({
  id: null,
  nickname: '',
  avatar: '',
  sex: null,
  email: '',
  phone: '',
  status: null,
  status1: null,
  address: '',
  roleId: null,
});
// 角色列表
const roleOptions = ref([]);
// 编辑弹框
const open1 = ref(false);
const rules = {
  userName: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'change',
    },
  ],
  nickName: [
    {
      required: true,
      message: '请输入昵称',
      trigger: 'change',
    },
  ],
  roleId: [
    {
      required: true,
      message: '请选择角色',
      trigger: 'change',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'change',
    },
  ],
};

const tableData = reactive({
  columns: computed(() => [
    {
      title: '序号',
      dataIndex: 'no',
      key: 'no',
      resizable: true,
      width: 60,
      customRender: ({ index }) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      maxWidth: 150,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      maxWidth: 150,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      maxWidth: 80,
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      maxWidth: 80,
    },
    {
      title: '性别',
      key: 'sex',
      dataIndex: 'sex',
      maxWidth: 80,
    },
    {
      title: '手机号',
      key: 'phone',
      dataIndex: 'phone',
      maxWidth: 100,
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
      maxWidth: 150,
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      maxWidth: 90,
    },
    {
      title: '操作',
      key: 'action',
      dataIndex: 'action',
      maxWidth: 80,
    },
  ]),
  data: [],
});

// 查询对象
const queryForm = reactive({
  pageModel: {
    pageNow: 1,
    pageSize: 10,
    query: {
      user_name0: '',
    }
  }
});

// 定义响应式的分页对象
const pagination = reactive({
  class: 'myPagination',
  total: 0, // 总条数
  current: 1, // 当前页数
  pageSize: 10, // 每页显示的条数
  // pageSizeOptions: ['10', '20', '30', '40', '50'],
  showSizeChanger: true, // 是否可以改变每页显示的条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: (total) => `共 ${total} 条`, // 显示总条数和当前数据范围
  onShowSizeChange: (current, pageSize) => handleShowSizeChange(current, pageSize), // 改变每页数量时更新显示
  onChange: (page, pageSize) => handleShowPageChange(page, pageSize) // 页码改变时的回调函数
});

// 处理每页显示条数改变的函数
const handleShowSizeChange = (current, pageSize) => {
  console.log(current, pageSize);
  pagination.pageSize = pageSize;
};

// 处理页码改变的函数
const handleShowPageChange = (page, pageSize) => {
  console.log('handleShowPageChange.', page, pageSize, isReturnFirstPage.value);
  expandedRowKeys.value = [];
  if (isReturnFirstPage.value) {
    pagination.current = 1;
    isReturnFirstPage.value = false;
  } else {
    pagination.current = page;
  }
};
const reset = () => {
  queryForm.pageModel.query.user_name0 = '';
  pagination.current = 1;
  getTableData();
}

const getTableData = () => {
  queryForm.pageModel.pageSize = pagination.pageSize;
  queryForm.pageModel.pageNow = pagination.current;
  findUserPage(queryForm).then((res) => {
    if (res.code === 200) {
      console.log(res.data);
      tableData.data = res.data.list.dataList;
    }
  }).catch((err) => {
    console.log(err);
  });
}
// 删除用户
const handleDeleteUser = (id) => {
  Modal.confirm({
    title: globalI18n.t('tips.deleteConfirm'),
    icon: h(ExclamationCircleOutlined),
    content: '',
    okText: `${globalI18n.t('common.confirm')}`,
    okType: 'danger',
    cancelText: `${globalI18n.t('common.cancel')}`,
    onOk() {
      deleteUser({ id }).then((res) => {
        if (res.code === 200 && res.data) {
          getTableData();
          message.success(globalI18n.t('tips.deleteSuccess'));
        }
      });
    },
    onCancel() { },
  });
}
// 展示编辑框
const showEditModel = (record) => {
  editRecord.id = record.id;
  editRecord.userName = record.userName;
  editRecord.nickName = record.nickName;
  editRecord.phone = record.phone;
  editRecord.email = record.email;
  editRecord.status = record.status;
  editRecord.status1 = record.status === 1 ? true : false;
  editRecord.sex = record.sex;
  editRecord.roleId = record.roleId;
  editRecord.remark = record.remark;
  modelTitle.value = '编辑用户';
  open1.value = true;
}
// 展示新增框
const showAddModel = () => {
  editRecord.id = '';
  editRecord.userName = '';
  editRecord.nickName = '';
  editRecord.phone = '';
  editRecord.email = '';
  editRecord.status = 1;
  editRecord.status1 = true;
  editRecord.sex = '';
  editRecord.roleId = '';
  editRecord.remark = '';
  modelTitle.value = '新增用户';
  open1.value = true;
}
const handleCancel = () => {
  open1.value = false;
}
// 添加/编辑用户
const handleAddUser = () => {
  formRef.value
    .validate()
    .then(() => {
      editRecord.status = editRecord.status1 ? 1 : 0;
      if (editRecord.id) {
        // 更新
        editUserInfo(editRecord).then(res => {
          if (res.code === 200) {
            message.success('编辑成功');
            open1.value = false;
            getTableData();
          } else {
            message.error('编辑失败');
          }
        }).catch(error => { console.log(error) });
      } else {
        // 新增
        addUser(editRecord).then(res => {
          if (res.code === 200) {
            message.success('添加成功');
            open1.value = false;
            getTableData();
          } else {
            message.error('添加失败');
          }
        }).catch(error => { console.log(error) });
      }
    })
    .catch(error => {
      console.log('error', error);
    });
}
// 获取角色列表
const getRoleList = () => {
  findRoleList().then(res => {
    if (res.code === 200) {
      roleOptions.value = res.data.map(e => { return { label: e.roleName, value: e.id } });
    }
  }).catch(err => {
    console.log(err);
  })
}

onMounted(() => {
  getTableData();
  getRoleList();
});
</script>

<style scoped lang="scss">
.userContainer {

  .searchRow {
    display: flex;
    background-color: #fff;
    padding: 20px;
    justify-content: space-between;
    margin-top: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    .inputRow {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .inputBox {
        display: flex;
        align-items: center;
        margin-right: 70px;
        margin-top: 10px;
        margin-bottom: 10px;

        .labelText {
          white-space: nowrap;
          font-size: 14px;
        }

        .selectClass {
          width: 199px;
        }
      }
    }

    .btnBox {
      display: flex;
      flex-wrap: nowrap;

      button {
        margin: 10px 0 10px 9px;
      }

      .ant-btn:first-child {
        margin-right: 8px !important;
      }
    }
  }

  .tableOperation {
    .custom-table {
      padding: 10px;
    }

    background-color: #fff;

    .operationBtn {
      display: flex;
      justify-content: right;
      margin-bottom: 20px;
    }

    padding: 20px;
  }

  // .actionBtn {
  //   color: #4ab44a;

  //   &:hover {
  //     color: #388b38;
  //   }
  // }
}
</style>
